package com.senthink.gl.business.api.controller;

import com.senthink.gl.business.auth.AuthService;
import com.senthink.gl.business.auth.LoginRequest;
import com.senthink.gl.business.auth.RegisterUserRequest;
import com.senthink.gl.business.response.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author Ethan
 * @date 2017/11/16
 */
@Api(tags = "用户授权Controller")
@RestController
public class AuthController {

    @Value("${jwt.header}")
    private String tokenHeader;
    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     *
     * @param loginRequest
     * @return
     */
    @ApiOperation(notes = "用户登录",value = "用户登录")
    @RequestMapping(value = "${uri.auth.login}", method = RequestMethod.POST)
    public ResponseEntity<?> login(@RequestBody @Valid LoginRequest loginRequest) {
        ApiResponse apiResponse = authService.login(loginRequest.getUsername(), loginRequest.getPassword());
        return ResponseEntity.ok(apiResponse);
    }

    /**
     * 用户注册(管理员添加用户)
     *
     * @param registerUserRequest
     * @return
     */
    @ApiOperation(notes = "用户注册(管理员添加用户)",value = "用户注册(管理员添加用户)")
    @RequestMapping(value = "${uri.auth.register}", method = RequestMethod.POST)
    public ResponseEntity<?> register(@RequestBody @Valid RegisterUserRequest registerUserRequest) {
        ApiResponse apiResponse = authService.register(registerUserRequest);
        return ResponseEntity.ok(apiResponse);
    }

    /**
     * 刷新Token
     *
     * @param request
     * @return
     */
    @ApiOperation(notes = "刷新Token",value = "刷新Token")
    @RequestMapping(value = "${uri.auth.refresh}", method = RequestMethod.GET)
    public ResponseEntity<?> refresh(HttpServletRequest request) {
        String str = RequestBody.class.toString();
        String oldToken = request.getHeader(tokenHeader);
        ApiResponse apiResponse = authService.refresh(oldToken);
        return ResponseEntity.ok(apiResponse);
    }

}
